import { app } from 'db://app-game/core/app';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { GameEvent } from '../../../../common/config/GameEvent';
import { smc } from '../../../singleton/SingletonModuleComp';
import { Inventory } from '../../inventory/Inventory';
import { Role } from '../../role/Role';
import { RoleStorageData } from '../../storage/LocalStorageManager.type';
import { Account } from '../Account';
import { AccountModelComp } from '../model/AccountModelComp';

/** 网络模式 */
export enum NetworkMode {
  /** 离线模型 */
  Offline = 0,
  /** 网络模式 */
  Online = 1,
}

/** 请求玩家游戏数据 */
@ecs.register('AccountNetData')
export class AccountNetDataComp extends ecs.Comp {
  /** 网络模式 */
  networkMode: NetworkMode.Offline;
  reset() {
    this.networkMode = NetworkMode.Offline;
  }
}

/** 请求玩家游戏数据系统 */
@ecs.register('Account')
export class AccountNetDataSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
  filter(): ecs.IMatcher {
    return ecs.allOf(AccountNetDataComp, AccountModelComp);
  }

  entityEnter(account: Account): void {
    let data;
    // 1.离线模式
    smc.storage.load();
    // 2.网络模式

    // 3.创建角色信息
    this.createRole(account);
    // 4.玩家登录成功事件
    app.message.dispatchEvent(GameEvent.LoginSuccess);
  }

  // 创建角色
  createRole(account: Account) {
    // TODO: 占时手写创建，后期从服务器获取
    const roleOne: RoleStorageData = {
      meta: {
        uid: 'ROLE_1',
        name: '角色1',
        classId: 0,
        created: '2025-03-25 10:00:00',
      },
      inventory: {
        items: [],
      },
      equipment: {
        weapon: 1,
        armor: -1,
        accessory: -1,
      },
      skills: [{ id: 0, level: 1 }],
      equipSkills: {
        current: 'firstSkillPack',
        firstSkillPack: {
          isUnlock: true,
          skills: {
            skillOneButton: { id: 0, level: 1 },
            skillTwoButton: { id: 0, level: 1 },
            skillThreeButton: { id: 0, level: 1 },
          },
        },
        secondSkillPack: {
          isUnlock: false,
          skills: {},
        },
      },
    };

    // 2.本地储存数据
    smc.storageData.roles.push(roleOne);
    smc.storageData.activeRole = 0;

    // 3.创建角色
    let role = ecs.getEntity<Role>(Role);
    let inventory = ecs.getEntity<Inventory>(Inventory);

    // 角色职业id
    role.RoleModelJob.id = roleOne.meta.classId;

    // 角色武器id
    role.RoleModelEquipment.weapon = roleOne.equipment.weapon;

    // 角色背包
    inventory.batchAddItem(roleOne.inventory.items);
    role.addInventory(inventory);

    account.AccountModel.role = role;

    // 角色基础属性绑定到界面上显示
    role.RoleModel.vmAdd();
  }
}
